package com.example.wemedia.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.wemedia.pojo.Channel;
import com.example.model.wemedia.pojo.News;
import com.example.wemedia.service.ChannelService;
import com.example.wemedia.service.NewsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "内容管理信息")
@RestController
@RequestMapping(value = "/api/v1")
public class ChannelController  {
    @Autowired
    private ChannelService channelService;
    @Autowired
    private NewsService newsService;

    @GetMapping(value = "/channel/getAllChannel")
    @Operation(summary= "获取所有频道信息")
    public R getAllChannel() {
        List<Channel> channelList = channelService.list();
        if (channelList != null) {
            return R.ok("查询所有频道成功").data("channelList", channelList);
        } else {
            return R.error("查询所有频道失败");
        }
    }

    @PostMapping(value = "/channel/addChannel")
    @Operation(summary = "增加频道")
    public R addChannel(@RequestBody Channel channel) {
        // 1\检查参数
        if (channel == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        LambdaQueryWrapper<Channel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Channel::getChannelName, channel.getChannelName());
        Channel channels = channelService.getOne(wrapper);
        if (channels != null) {
            return R.error(ResultCodeRecord.DATA_EXIST, "频道已存在");
        }
        boolean flag = channelService.save(channel);
        channel.setCreatedTime(new Date());
        if (flag) {
            return R.ok("增加频道成功");
        } else {
            return R.error("增加频道失败");
        }
    }

    @DeleteMapping("/channel/deleteChannel/{channelId}")
    @Operation(summary = "删除频道")
    public R deleteChannel(@PathVariable(value = "channelId") Integer channelId) {
        // 1、检查参数
        if (channelId == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 2、查询频道
        Channel channel = channelService.getById(channelId);
        if (channel == null) {
            return R.error(ResultCodeRecord.DATA_NOT_EXIST, "频道不存在");
        }
        // 3、频道是否有效
        if (channel.getChannelStatus()) {
            return R.error(ResultCodeRecord.PARAM_INVALID, "频道有效，无法删除");
        }
        // 判断是否被引用
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(News::getChannelId, channelId)
                .eq(News::getNewsStatus, News.NewsStatus.PUBLISHED.getCode());
        boolean isReferenced = newsService.count(wrapper) > 0;
        if (isReferenced) {
            return R.error(ResultCodeRecord.PARAM_INVALID, "频道被引用，无法删除");
        }
        boolean flag = channelService.removeById(channelId);
        if (flag) {
            return R.ok("删除频道成功");
        } else {
            return R.error("删除频道失败");
        }
    }

    @GetMapping("/channel/getByChannelId/{channelId}")
    @Operation(summary = "按照频道编号查看")
    public R getByChannelId(@PathVariable(value = "channelId") Integer channelId) {
        Channel channel = channelService.getById(channelId);
        if (channel != null) {
            return R.ok("查询频道成功").data("channel", channel);
        } else {
            return R.error("查询频道失败");
        }
    }

    @PutMapping("/channel/updateChannel")
    @Operation(summary = "修改频道")
    public R updateChannel(@RequestBody Channel channel) {
        // 1、检查参数
        if (channel == null || channel.getChannelId() == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 2、查询频道
        LambdaQueryWrapper< News > wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(News::getChannelId, channel.getChannelId())
                .eq(News::getNewsStatus, News.NewsStatus.PUBLISHED.getCode());
        boolean isReferenced = newsService.count(wrapper) > 0;
        if (isReferenced) {
            return R.error(ResultCodeRecord.PARAM_INVALID, "频道被引用不能修改或者急用");
        }
        boolean flag = channelService.updateById(channel);
        if (flag) {
            return R.ok("修改频道成功");
        } else {
            return R.error("修改频道失败");
        }
    }

    @PostMapping("/channel/getChannelPage/{page}/{pageSize}")
    @Operation(summary = "查询模糊频道分页")
    public R getChannelPage(@RequestBody String channelName, @PathVariable(value = "page") Long page, @PathVariable(value = "pageSize") Long pageSize) {
        // 1、 检查参数是否有效
        if (channelName == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 2、分页查询
        Page <Channel> channelPage = new Page<>(page, pageSize);
        // 3、条件构造器
        LambdaQueryWrapper<Channel> wrapper = new LambdaQueryWrapper<>();
        // 模糊频道查询
        if (StringUtils.isNotBlank(channelName)) {
            wrapper.like(Channel::getChannelName, channelName);
        }
        // 排序
        wrapper.orderByDesc(Channel::getCreatedTime);
        // 查询数据
        channelService.page(channelPage, wrapper);
        // 每页的数据集合
        List< Channel > channelList = channelPage.getRecords();
        // 总的记录数
        Long total = channelPage.getTotal();
        //每页条数
        Long size = channelPage.getSize();
        // 总页数
        Long pages = channelPage.getPages();
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("pageSize", size);
        map.put("pages", pages);
        map.put("page", page);
        map.put("channelList", channelList);
        if (map != null) {
            return R.ok("查询模糊频道分页成功").data(map);
        } else {
            return R.error("查询模糊频道分页失败");
        }
    }
}
